package com.ruoyi.test.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.test.domain.ParamEdit;
import com.ruoyi.test.mapper.ParamEditMapper;
import com.ruoyi.test.service.IParamEditService;
import com.ruoyi.test.service.IdataInsertService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class dataInsertServiceImpl implements IdataInsertService {

    @Autowired
    private IParamEditService paramEditService;
    @Autowired
    private ParamEditMapper paramEditMapper;

    @Override
    @Test
    public void handleJson(Long id){
        String jsonStr = interfaceUtil("http://116.63.174.61:9004/mpsParameter", "", "GET");
//        String jsonStr = "{\"page_index\":\"1\",\"rows_per_page\":\"20\",\"row_count\":\"86\",\"errmsg\":\"\",\"errcode\":\"0\",\"page_count\":\"5\",\"consignmentlist\":[{\"remark\":null,\"state\":\"Opening\",\"sum\":\"46288.0000\",\"code\":\"0000000081\",\"date\":\"2015-11-16\",\"operation_type\":\"普通销售\",\"cusabbname\":\"淘宝\",\"saletype\":\"01\",\"personcode\":null,\"custcode\":\"0901\",\"cusname\":\"淘宝网\",\"deptcode\":\"0303\",\"salename\":\"普通销售\",\"money\":\"39562.4000\",\"personname\":null,\"deptname\":\"订单中心\",\"maker\":\"demo\",\"verifier\":\"demo\",\"closer\":\"demo\"},{\"remark\":null,\"state\":\"Opening\",\"sum\":\"46288.0000\",\"code\":\"0000000087\",\"date\":\"2015-11-13\",\"operation_type\":\"普通销售\",\"cusabbname\":\"淘宝\",\"saletype\":\"01\",\"personcode\":null,\"custcode\":\"0901\",\"cusname\":\"淘宝网\",\"deptcode\":\"0303\",\"salename\":\"普通销售\",\"money\":\"39562.4000\",\"personname\":null,\"deptname\":\"订单中心\",\"maker\":\"demo\",\"verifier\":\"demo\",\"closer\":\"demo\"}]}";
        JSONObject jobj = JSON.parseObject(jsonStr);
        JSONArray consignmentlist = jobj.getJSONArray("data");
        System.out.println(consignmentlist);
        String tableName = "interface"+String.valueOf(id);
        paramEditMapper.deleteTable(tableName);
//        System.out.println(map.get("code1"));
        List<ParamEdit> list =paramEditMapper.selectTableParam(id);
//        System.out.println(list.get(0).getparamName());
        List<String> paramList=list.stream().map(ParamEdit::getParamName).collect(Collectors.toList());
//        System.out.println(paramList);
        Map<String, String> insertMap = new HashMap<>();
        for(int j = 0;j<consignmentlist.size();j++){
            Map map = (Map) consignmentlist.get(j);
            for (int i = 0; i <paramList.size() ; i++) {
                if (map.get(paramList.get(i))!=null){
                    insertMap.put(paramList.get(i),String.valueOf(map.get(paramList.get(i))));
                }
            }
            Map<String, Object> columnMap = new HashMap<>();

            Map<String,String> idMap = new HashMap<>();
            idMap.put("id", tableName);
            columnMap.put("id", idMap);
            columnMap.put("columnMap", insertMap);
            paramEditMapper.insertMap(columnMap);
        }



    }

    /**
     * @调用对方接口方法  向指定 URL发送请求，请求参数为json形式数据
     * @param path 对方或第三方提供的路径
     * @param param 向对方或第三方发送的数据，大多数情况下给对方发送JSON数据让对方解析
     * @param requestMethod 请求方式 GET POST PUT等
     * @return
     */
    public  String interfaceUtil(String path, String param, String requestMethod) {
        String objectData = "";
        try {
            URL url = new URL(path);

            //打开和url之间的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;

            //设置URLConnection的参数和普通的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            if(requestMethod == "POST") {//发送POST方式的请求，需要获取URLConnection实例对应的输出流来发送请求参数
                //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，发送post请求必须设置这两个
                //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
                //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
                connection.setDoOutput(true);
                connection.setDoInput(true);

                connection.setRequestMethod("POST");//GET和POST必须全大写
                out = new PrintWriter(connection.getOutputStream());//获取URLConnection对象对应的输出流
                out.print(param);//发送请求参数即数据
                out.flush();//缓冲数据
            }else if(requestMethod == "GET") {//发送GET方式请求，使用connet方法建立和远程资源之间的实际连接即可
                connection.setRequestMethod("GET");//GET和POST必须全大写
                connection.connect();
            }else {
                System.out.println("请重新设置请求方式！");
            }

            //获取URLConnection对象对应的输入流
            InputStream is = connection.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                str = new String(str.getBytes(), "UTF-8");//解决中文乱码问题
                System.out.println("str:" + str);
                objectData = getStringData(str);
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            connection.disconnect();
            System.out.println(requestMethod+"接口调用完毕！");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return objectData;
    }


    public static String getStringData(String value) {
        return value;
    }
}
